package learn.mqtt.service.impl;

import com.google.common.base.Throwables;
import learn.mqtt.MqttEmm;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

@Service
public class ConsumerServiceImpl implements MqttCallback {

    public ConsumerServiceImpl(MqttClient mqttClient) {
        mqttClient.setCallback(this);
        try {
            mqttClient.subscribe(MqttEmm.TOP_ID1.getTopIcName());
        } catch (MqttException e) {
            System.out.println(Throwables.getStackTraceAsString(e));
        }
    }

    @Override
    public void connectionLost(Throwable throwable) {
        // 连接失败
        System.out.println("connectionLost");
        System.out.println(throwable.getMessage());
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {
        System.out.println("topIc name:\t" + topic);
        String message = new String(mqttMessage.getPayload(), StandardCharsets.UTF_8);
        System.out.println(message);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        // 链接成功
        System.out.println("deliveryComplete");
    }
}
